package cn.edu.lingnan.controllerV1;


import cn.edu.lingnan.constant;
import cn.edu.lingnan.service.EmailService;
import cn.edu.lingnan.service.LoginService;

import cn.edu.lingnan.user.dtos.LoginDto;
import cn.edu.lingnan.user.dtos.RegisterDto;
import cn.edu.lingnan.user.dtos.Result;
import cn.edu.lingnan.user.vos.MenuVO;
import cn.edu.lingnan.user.vos.UserInfoVo;

import jakarta.mail.MessagingException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.security.Permission;
import java.util.List;

@RestController
@RequestMapping("/auth")
@Slf4j
@CrossOrigin
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private EmailService emailService;

    @PostMapping("/login")
    public Result<UserInfoVo> login(@RequestBody LoginDto loginDto, HttpServletRequest request) {

        // 获取当前会话的 sessionId
        String sessionId = request.getSession().getId();
        log.info("验证码请求：{}", sessionId);


        // 从 Redis 中获取存储的验证码
        String storedCaptcha = (String) redisTemplate.opsForValue().get("captcha:" + sessionId);

        // 验证验证码（忽略大小写）
        if (loginDto.getCaptcha() == null || !loginDto.getCaptcha().equalsIgnoreCase(storedCaptcha)) {
            return Result.error("验证码错误或已过期，请重新输入！");
        }

        // 验证通过后，删除 Redis 中的验证码，防止重复使用
        redisTemplate.delete("captcha:" + sessionId);

        log.info("Login request received: {}", loginDto);
         UserInfoVo userInfoVo = loginService.login(loginDto);
        if (userInfoVo == null) {
            return Result.error(constant.USERNAME_OR_PASSWORD_ERROR);
        }
        if (userInfoVo.getDelFlag() == 1) {
            return Result.unauthorized(constant.USER_NOT_EXIST);
        }
        if (userInfoVo.getStatus() == 0) {
            return Result.error(constant.USER_DISABLED);
        }

        userInfoVo.setUserPassword(null);
        userInfoVo.setSalt(null);
        userInfoVo.setDelFlag(null);
        return Result.success(userInfoVo);
    }

    @GetMapping("/menus")
    public Result<List<MenuVO>> getUserMenus(@RequestParam("userId") Integer userId) {
        return Result.success(loginService.getMenusByUserId(userId));
    }

    //权限管理
    @GetMapping("/permissions")
    public Result<List<String>> getUserRoutes(@RequestParam("userId") Integer userId) {
        return Result.success(loginService.findPermissionsByUserId(userId));
    }



}
